import { S, U, getRequestId, mapField } from '../../lib/backend'
import Q from 'q'
import axios from 'axios'
import env from '../../config/common'

export default {
  getChannels ({ commit, state, rootState }, info) {
    const API_HOST = env.CRM_API_HOST
    const frag = '?' + U(info)
    // const API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/17991/'
    return Q.Promise((success, error) => {
      axios.get(
         API_HOST + '/users/' + rootState.auth.user.token + '/channels' + frag
      ).then((response) => {
        if (response.data.results) {
          const data = response.data.results
          response.data.results = data
        }
        success(response)
      }).catch((err) => {
        error(err)
        console.log(err)
      })
    })
  },
  getUndefinedChannels ({ commit, state, rootState }, info) {
    const API_HOST = env.CRM_API_HOST
    const frag = '?' + U(info)
    // const API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/17991/'
    return Q.Promise((success, error) => {
      axios.get(
         API_HOST + '/users/' + rootState.auth.user.token + '/undefined_channels' + frag
      ).then((response) => {
        if (response.data.results) {
          const data = response.data.results
          response.data.results = data
        }
        success(response)
      }).catch((err) => {
        error(err)
        console.log(err)
      })
    })
  },
  saveChannel ({ commit, state, rootState }, info) {
    const API_HOST = env.CRM_API_HOST
    let frag = ''
    if (typeof info.id !== 'undefined') {
      frag = '/' + info.id
    }
    const params = S(info)
    // const API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/17991/'
    return Q.Promise((success, error) => {
      axios.post(
         API_HOST + '/users/' + rootState.auth.user.token + '/channels' + frag,
         params
      ).then((response) => {
        success(response)
      }).catch((err) => {
        error(err)
        console.log(err)
      })
    })
  },
  deleteChannel ({ commit, state, rootState }, info) {
    const API_HOST = env.CRM_API_HOST
    const frag = '/' + info.id
    // const API_HOST = 'http://120.24.48.9:8889/http://rapapi.org/mockjsdata/17991/'
    return Q.Promise((success, error) => {
      axios.delete(
         API_HOST + '/users/' + rootState.auth.user.token + '/channels' + frag
      ).then((response) => {
        success(response)
      }).catch((err) => {
        error(err)
        console.log(err)
      })
    })
  }
}
